package com.hengtiansoft.lfy.chart.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hengtiansoft.lfy.LFYApplication;
import com.hengtiansoft.lfy.R;
import com.hengtiansoft.lfy.base.BaseActivity;
import com.hengtiansoft.lfy.constants.Constants;
import com.hengtiansoft.lfy.utils.Config;
import com.hengtiansoft.lfy.utils.JsonParser;
import com.hengtiansoft.lfy.utils.Kdxf_TTSPlayer;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;

import java.io.File;

/**
 * @ClassName: VoiceDialogActivity
 * @Description: 语音识别dialog
 * @author caijiajun
 * @date 2015年12月3日 下午2:14:38
 * 
 */
public class VoiceDialogActivity extends FragmentActivity
        implements OnClickListener {
    private final static String TAG = com.hengtiansoft.lfy.activity.Kdxf_VoiceDialogActivity.class.getSimpleName();
    private TextView mTvText;
    private ImageView mTranslateRecordingVoiceImg;
    private LinearLayout mRlCancel;//取消
    private Button mRlSubmit;
    private Drawable[] micImages;
   private String transferType;

    /**
     * 用来判断是否发送信息
     */
    private String from;
    /**
     * 要发送目标
     */
    private String toChatUsername;
    private Long date;
    public static final String Basic_PATH = Environment
            .getExternalStorageDirectory().getAbsolutePath() + File.separator
            + "longfanyi/voice/";
    public static final String Basic_PATH_data = "/data/data/com.hengtiansoft.lfy/longfanyi/voice/";
    String url;
    /*--------------科大讯飞--------------------*/
    // 语音听写对象
    private SpeechRecognizer mIat;
    public String kdxf_transferType="zh_cn";
    // 引擎类型
    private String mEngineType = SpeechConstant.TYPE_CLOUD;
    //是否取消语音识别
    private boolean iscanelVoice=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_voice_old);
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay(); // 为获取屏幕宽、高
        WindowManager.LayoutParams p = getWindow().getAttributes();
        // p.height = (int) (d.getHeight() * 0.5); // 高度设置为屏幕的0.3
        p.width = (int) (d.getWidth() * 0.7); // 宽度设置为屏幕的0.7
        getWindow().setAttributes(p);
        initView();
        setListener();
    }

    private void initView() {
        // 动画资源文件,用于录制语音时
        micImages = new Drawable[] {
                getResources().getDrawable(R.color.transparent),
                getResources().getDrawable(R.drawable.icon_voice1),
                getResources().getDrawable(R.drawable.icon_voice1),
                getResources().getDrawable(R.drawable.icon_voice2),
                getResources().getDrawable(R.drawable.icon_voice2),
                getResources().getDrawable(R.drawable.icon_voice2),
                getResources().getDrawable(R.drawable.icon_voice2),
                getResources().getDrawable(R.drawable.icon_voice2),
                getResources().getDrawable(R.drawable.icon_voice2),
        };
        mRlCancel = (LinearLayout) findViewById(
                R.id.rl_translate_recording_voice_cancel); //取消
        mRlSubmit = (Button) findViewById(
                R.id.rl_translate_recording_voice_submit);//说完了
        mTranslateRecordingVoiceImg = (ImageView) findViewById(
                R.id.translate_recording_voice_img); //话筒半圆
        mTvText = (TextView) findViewById(R.id.tv_translate_recording_hint); //提示文字
        transferType = getIntent().getStringExtra("transferType"); //翻译类型
        date = getIntent().getLongExtra("date", System.currentTimeMillis());
        Log.i(TAG, System.currentTimeMillis() + "");
        from = getIntent().getStringExtra("from");
        toChatUsername = getIntent().getStringExtra("toChatUsername");
        String path = Basic_PATH_data
                + Config.getUserName() + "/"; //存贮目录
        File destDir = new File(path);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        url = path + System.currentTimeMillis() + ".wav"; //文件路径
        // ztRecognizer.setPath(url);
        if (transferType.equals("ench")) {
            mTvText.setText(getString(R.string.move_up_to_cancel_en));
            //mRlCancel.setText(getString(R.string.canel_en));
            mRlSubmit.setText(getString(R.string.done_en));
            kdxf_transferType="en_us";
        } else {
            kdxf_transferType="zh_cn";
        }

        startVoice();
    }

    private void setListener() {
        mRlCancel.setOnClickListener(this);
        mRlSubmit.setOnClickListener(this);
    }
    public String result="";
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.rl_translate_recording_voice_cancel:
            if (transferType.equals("ench")) {
                mTvText.setText(getString(R.string.processing_en));
            } else {
                mTvText.setText(getString(R.string.processing));
            }
            stopVoiceNoResult();
            break;
        case R.id.rl_translate_recording_voice_submit:
            // pcmToAAC();
            if (transferType.equals("ench")) {
                mTvText.setText(getString(R.string.processing_en));
            } else {
                mTvText.setText(getString(R.string.processing));
            }
            stopVoice();
            break;
        default:
            break;
        }
    }

    /**
     * 开始录音
     */
    public void startVoice() {
        //-------------------------------------科大讯飞
        //TTSPlayer.getInstense().stop();//语音播放停止
        Kdxf_TTSPlayer.getInstense().stop();
        // 初始化识别无UI识别对象
        // 使用SpeechRecognizer对象，可根据回调消息自定义界面；
        mIat = SpeechRecognizer.createRecognizer(this, mInitListener);
        setParam();
        mIat.startListening(recognizerListener);
    }
    //监听器
    private RecognizerListener recognizerListener=new RecognizerListener() {
        //volume音量值0~30， data音频数据
        @Override
        public void onVolumeChanged(int i, byte[] bytes) {
            mTranslateRecordingVoiceImg
                    .setImageDrawable(micImages[i/4]);
        }
        //开始录音
        @Override
        public void onBeginOfSpeech() {
            Log.i("supeng","onBeginOfSpeech");
        }
        //结束录音
        @Override
        public void onEndOfSpeech() {
            Log.i("supeng","onEndOfSpeech");
            if(iscanelVoice){
                Intent intent = new Intent();
                intent.putExtra("result", Constants.ZR_STOP_NULL);
                setResult(RESULT_OK, intent);
                finish();
                return;
            }
        }
        //一般情况下会通过onResults接口多次返回结果，完整的识别内容是多次结果的累加；
        //关于解析Json的代码可参见Demo中JsonParser类；
        //isLast等于true时会话结束。
        @Override
        public void onResult(RecognizerResult recognizerResult, boolean isLast) {
            result=result+getStringResult(recognizerResult);
            if (isLast) {
                if(iscanelVoice){
                    Intent intent = new Intent();
                    intent.putExtra("result", Constants.ZR_STOP_NULL);
                    setResult(RESULT_OK, intent);
                    finish();
                    return;
                }
               // String recoResult = result; //翻译后的文字
                String Basic_PATH = url;//压缩过后的原始音频
                Log.i("supeng","url="+url+",res="+result);
                String[] a = Basic_PATH.split("/");
                int i = a.length;
                int j = i - 1;
                Intent intent = new Intent();
                intent.putExtra("result", result);
                intent.putExtra("url", Basic_PATH);
                intent.putExtra("fileName", a[j]);//文件名
                Log.i(TAG, "Basic_PATH:" + Basic_PATH + "fileName" + a[j]);
                setResult(RESULT_OK, intent);
                finish();
            }
        }
        //会话发生错误回调接口
        // Tips：
        // 错误码：10118(您没有说话)，可能是录音机权限被禁，需要提示用户打开应用的录音权限。
        // 如果使用本地功能（语记）需要提示用户开启语记的录音权限。
        @Override
        public void onError(SpeechError speechError) {
            Log.i("supeng","error="+speechError.getErrorCode());
            if(iscanelVoice){
                Intent intent = new Intent();
                intent.putExtra("result", Constants.ZR_STOP_NULL);
                setResult(RESULT_OK, intent);
                finish();
                return;
            }
            if("10118".equals(speechError.getErrorCode()+"")){
                //Toast.makeText(Dialog_Voice_Activity.this, "您没有说话", Toast.LENGTH_LONG).show();
                String res= "No_RESULT";
                Intent intent = new Intent();
                intent.putExtra("result", Constants.No_RESULT);
                setResult(RESULT_OK, intent);
                finish();
            }else{
                Intent intent = new Intent();
                intent.putExtra("result", Constants.ZR_ERROR);
                setResult(RESULT_OK, intent);
                finish();
               // Toast.makeText(Dialog_Voice_Activity.this,"异常"+speechError.getPlainDescription(true),Toast.LENGTH_LONG).show();
            }
            finish();
        }
        //扩展用接口
        @Override
        public void onEvent(int i, int i1, int i2, Bundle bundle) {

        }
    };
    private String getStringResult(RecognizerResult results) {
        String text = JsonParser.parseIatResult(results.getResultString());
        return text;

    }
    /**
     * 初始化监听器。
     */
    private InitListener mInitListener = new InitListener() {

        @Override
        public void onInit(int code) {
            Log.d(TAG, "SpeechRecognizer init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                Log.d(TAG, "初始化失败");
            }
        }
    };
    private void setParam() {
        // 清空参数
        mIat.setParameter(SpeechConstant.PARAMS, null);

        // 设置听写引擎
        mIat.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
        // 设置返回结果格式
        mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");


        // 设置语言
        mIat.setParameter(SpeechConstant.LANGUAGE, kdxf_transferType);
        if(kdxf_transferType.equals("zh_cn")) {
            // 设置语言区域
            mIat.setParameter(SpeechConstant.ACCENT, "mandarin");
        }

        // 设置语音前端点:静音超时时间，即用户多长时间不说话则当做超时处理
        mIat.setParameter(SpeechConstant.VAD_BOS, "5000");

        // 设置语音后端点:后端点静音检测时间，即用户停止说话多长时间内即认为不再输入， 自动停止录音
        mIat.setParameter(SpeechConstant.VAD_EOS, "2000");

        // 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mIat.setParameter(SpeechConstant.ASR_PTT, "1");

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mIat.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH,url);
    }
    /**
     * 停止并返回数据
     */
    public void stopVoice() {
        //---------------------------------
        mIat.stopListening();//停止识别
    }

    /**
     * 停止不返回数据
     */
    public void stopVoiceNoResult() {
        //------------------------------
        iscanelVoice=true;
        mIat.cancel();//取消识别
        Intent intent = new Intent();
        intent.putExtra("result", Constants.ZR_STOP_NULL);
        setResult(RESULT_OK, intent);
        finish();

    }




}
